import fs from 'fs';
const path = '/Users/kangqing/workspace/llm_pc/frontend/src/views/Home_Optimized.vue';

// 读取文件内容
const content = fs.readFileSync(path, 'utf8');
const lines = content.split('\n');

// 计算div标签平衡
let openDivCount = 0;
let closeDivCount = 0;
let balance = 0;
let maxBalance = 0;
let lastOpenLine = 0;

console.log('分析div标签平衡...');

for (let i = 0; i < lines.length; i++) {
  const line = lines[i];
  
  // 跳过注释行
  if (line.trim().startsWith('//') || line.trim().startsWith('/*') || line.trim().startsWith('*')) {
    continue;
  }
  
  // 跳过style和script标签内的内容
  if (line.includes('<style') || line.includes('<script')) {
    break; // 我们只关心template部分
  }
  
  const openMatches = line.match(/<div\b[^>]*>/g) || [];
  const closeMatches = line.match(/<\/div>/g) || [];
  
  openDivCount += openMatches.length;
  closeDivCount += closeMatches.length;
  balance += openMatches.length - closeMatches.length;
  
  if (balance > maxBalance) {
    maxBalance = balance;
  }
  
  if (openMatches.length > 0) {
    lastOpenLine = i + 1;
  }
}

console.log(`模板部分统计:`);
console.log(`打开的<div>标签: ${openDivCount}`);
console.log(`关闭的</div>标签: ${closeDivCount}`);
console.log(`不平衡数量: ${balance}`);
console.log(`最大嵌套深度: ${maxBalance}`);
console.log(`最后一个<div>标签在: 第${lastOpenLine}行`);

// 找到template的结束位置
let templateEndIndex = -1;
for (let i = 0; i < lines.length; i++) {
  if (lines[i].trim() === '</template>') {
    templateEndIndex = i;
    break;
  }
}

if (templateEndIndex !== -1 && balance > 0) {
  console.log(`需要在第${templateEndIndex}行前添加 ${balance} 个 </div> 标签`);
  
  // 添加缺失的闭合标签
  const newLines = [...lines];
  for (let i = 0; i < balance; i++) {
    newLines.splice(templateEndIndex, 0, '  </div>');
  }
  
  // 写回文件
  fs.writeFileSync(path, newLines.join('\n'));
  console.log('修复完成！');
} else if (balance < 0) {
  console.log('错误：关闭了比打开更多的div标签！');
} else {
  console.log('div标签已经平衡，无需修复');
}